//
//  ANFindPsdController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/14.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANFindPsdController.h"
#import "LoginTextField.h"
#import "ANGradientButton.h"

@interface ANFindPsdController ()

@property (nonatomic, strong) UIImageView *icon;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) LoginTextField *telTextField;

@property (nonatomic, strong) LoginTextField *psdTextField;

@property (nonatomic, strong) LoginTextField *psdAgainTextField;

@property (nonatomic, strong) LoginTextField *codeTextField;

@property (nonatomic, strong) ANGradientButton *sureButton;

@property (nonatomic, strong) dispatch_source_t timer;

@end

@implementation ANFindPsdController

- (void)dealloc
{
    if (self.timer) {
        dispatch_cancel(self.timer);
        self.timer = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"找回密码";
    
    WeakSelf
    self.codeTextField.getCodeHandle = ^(ANGradientButton * _Nonnull sender) {
        [weakSelf getSms];
    };
}

- (void)getSms
{
    NSString *phone = self.telTextField.textField.text;
    if (phone.length != 11) {
        [MBProgressHUD showWarning:@"请输入正确的手机号码"];
        return;
    }
    NSDictionary *body = @{
                           @"phone":phone
                           };
    [MBProgressHUD showActivityMessage:@"正在请求..."];
    [URLManager.shareManager postUrlStr:Api_GetSmsCode parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                [self creatTimer];
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
    }];
}

- (void)creatTimer
{
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0*NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(1.0*NSEC_PER_SEC);
    dispatch_source_set_timer(self.timer, start, interval, 0);
    WeakSelf
    __block int sec = 60;
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"%d",sec);
        sec--;
        [weakSelf.codeTextField.rightView setTitle:[NSString stringWithFormat:@"%d (s)",sec] forState:UIControlStateNormal];
        weakSelf.codeTextField.rightView.enabled = false;
        if (sec == 0) {
            dispatch_cancel(weakSelf.timer);
            weakSelf.timer = nil;
            [weakSelf.codeTextField.rightView setTitle:@"获取验证码" forState:UIControlStateNormal];
            weakSelf.codeTextField.rightView.enabled = YES;
        }
        
    });
    dispatch_resume(self.timer);
}

- (void)setupSubViews
{
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.icon = [[UIImageView alloc] init];
    self.icon.image = [UIImage imageNamed:@"logo"];
    [self.scrollView addSubview:self.icon];
    [self.icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.scrollView);
        make.top.equalTo(self.scrollView).offset(kWidth(30));
    }];
    
    self.telTextField = [[LoginTextField alloc] init];
    self.telTextField.type = LoginTextFieldFindTel;
    [self.scrollView addSubview:self.telTextField];
    [self.telTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.icon.mas_bottom).offset(kWidth(50));
        make.centerX.equalTo(self.scrollView);
        make.left.equalTo(self.scrollView).offset(kWidth(15));
        make.right.equalTo(self.scrollView).offset(-kWidth(15));
        make.height.equalTo(@(kWidth(48)));
        make.width.equalTo(@(kScreenW-kWidth(30)));
    }];
    
    self.psdTextField = [[LoginTextField alloc] init];
    self.psdTextField.type = LoginTextFieldFindPsd;
    [self.scrollView addSubview:self.psdTextField];
    [self.psdTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.telTextField.mas_bottom).offset(kWidth(20));
        make.centerX.equalTo(self.scrollView);
        make.left.equalTo(self.scrollView).offset(kWidth(15));
        make.right.equalTo(self.scrollView).offset(-kWidth(15));
        make.height.equalTo(@(kWidth(48)));
    }];
    
    self.psdAgainTextField = [[LoginTextField alloc] init];
    self.psdAgainTextField.type = LoginTextFieldFindPsdAgain;
    [self.scrollView addSubview:self.psdAgainTextField];
    [self.psdAgainTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.psdTextField.mas_bottom).offset(kWidth(20));
        make.centerX.equalTo(self.scrollView);
        make.left.equalTo(self.scrollView).offset(kWidth(15));
        make.right.equalTo(self.scrollView).offset(-kWidth(15));
        make.height.equalTo(@(kWidth(48)));
    }];
    
    self.codeTextField = [[LoginTextField alloc] init];
    self.codeTextField.type = LoginTextFieldFindCode;
    [self.scrollView addSubview:self.codeTextField];
    [self.codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView).offset(kWidth(15));
        make.right.equalTo(self.scrollView).offset(-kWidth(15));
        make.top.equalTo(self.psdAgainTextField.mas_bottom).offset(kWidth(20));
        make.height.equalTo(@(kWidth(48)));
    }];
    
    self.sureButton = [[ANGradientButton alloc] initWithFrame:CGRectMake(0, 0, kScreenW-kWidth(30), kWidth(48))];
    [self.sureButton setTitle:@"确认" forState:UIControlStateNormal];
    [self.sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.sureButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [self.scrollView addSubview:self.sureButton];
    [self.sureButton addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeTextField.mas_bottom).offset(kWidth(60));
        make.left.equalTo(self.scrollView).offset(kWidth(15));
        make.right.equalTo(self.scrollView).offset(-kWidth(15));
        make.height.equalTo(@(kWidth(48)));
        make.bottom.equalTo(self.scrollView).offset(-kWidth(40));
    }];
    self.sureButton.layer.cornerRadius = kWidth(24);
    self.sureButton.layer.masksToBounds = YES;
}

- (void)sureAction
{
    if (self.telTextField.textField.text.length < 1) {
        [MBProgressHUD showError:@"请输入账号"];
        return;
    }
    if (self.psdTextField.textField.text.length < 1) {
        [MBProgressHUD showError:@"请输入新密码"];
        return;
    }
    if (self.psdAgainTextField.textField.text.length < 1) {
        [MBProgressHUD showError:@"请再次确认密码"];
        return;
    }
    if (![self.psdTextField.textField.text isEqualToString:self.psdAgainTextField.textField.text]) {
        [MBProgressHUD showError:@"两次输入的密码不一致，请确认"];
        return;
    }
    if (self.codeTextField.textField.text.length < 1) {
        [MBProgressHUD showError:@"请输入短信验证码"];
        return;
    }
    NSDictionary *body = @{
                           @"userName":self.telTextField.textField.text,
                           @"password":self.psdTextField.textField.text,
                           @"code":self.codeTextField.textField.text
                           };
    [MBProgressHUD showActivityMessage:nil];
    [URLManager.shareManager postUrlStr:Api_User_Find parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                [MBProgressHUD showSuccess:responseObj[@"message"]];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else {
                [MBProgressHUD showError:responseObj[@"message"]];
            }
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
